#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>

typedef int HeapDateType;

void Swap(int* p1, int* p2)
{
	assert(p1 && p2);
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}


void AdjustDown(HeapDateType* a, int n, int parent)
{
	assert(a);
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
		{
			child += 1;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}

}




void HeapSort(int* a, int len)
{
	assert(a);
	int parent = (len - 2) / 2;
	while (parent >= 0)
	{
		AdjustDown(a, len, parent);
		parent -= 1;
	}
	int end = len - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		end--;
		AdjustDown(a, end+1,0);
	}

}



int main()
{
	int a[] = { 2,0,3,8,9,10,60,50,20,10 };
	int len = sizeof(a) / sizeof(a[0]);
	HeapSort(a, len);
	int i = 0;
	for (i = 0; i < len; i++)
	{
		printf("%d ", a[i]);
	}
	
	return 0;
}